package yxy.game.pm2.command.altar;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.debris;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.AltarMessage;
import yxy.game.pm2.message.PackageMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.PackageHandle;

import java.util.Collection;

/** 祭坛 将魂献祭执行 */
@MessageType(proto = Command.AltarChipDo, classtype = AltarMessage.AltarChipDoRequest.class)
public class CMD_AltarChipDo extends Command<AltarMessage.AltarChipDoRequest> {

	@Override
	public void execute(MessageSource messageSource, AltarMessage.AltarChipDoRequest request) {
		String playerCode = messageSource.getTag();
		PackageMessage.Item item = request.getItem();

		AltarMessage.AltarChipDoResponse.Builder response = AltarMessage.AltarChipDoResponse.newBuilder();

		try {
			CurrencyType type = CurrencyType.forNumber(item.getType());
			if (type == null || !type.equals(CurrencyType.CT_碎片)) {
				send(messageSource, response, Result.ParamError);
				return;
			}
			debris data = DataCenter.getData(item.getDataId(), debris.class);
			if (data == null) {
				send(messageSource, response, Result.ParamError);
				return;
			}
			Currency cost = Currency.create(type, data.getId(), item.getNumber());
			try {
				new CurrencyHandle().cost(playerCode, CCReason.祭坛, cost);
			} catch (CurrencyNotEnoughException e) {
				send(messageSource, response, new Result(Result.CostFail, e.getType().getNumber(), e.getDataId()));// 消费不足
				return;// 献祭的碎片数量不足
			}

			Collection<Currency> back = Currency.create(data.getDegenerationcost(), data.getDegenerationid(), data.getDegenerationnum());
			for (Currency bc : back) {
				bc.setNumber(bc.getNumber() * item.getNumber());
			}
			new CurrencyHandle().addCurrency(playerCode, CCReason.祭坛, back);

			response.addAllBack(new CurrencyHandle().packItems(back));
			response.setPack(new PackageHandle().getPackage(playerCode, CurrencyType.CT_碎片));

			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, AltarMessage.AltarChipDoResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}